<?php

namespace app\Index\controller;

use think\Controller;
use think\Db;
use think\Request;

class User extends Controller
{
    private $mem;

    public function initialize()
    {
        $this->mem = new \Memcache();
        $this->mem->connect('127.0.0.1','11211');
        dump(session("mobile"));
        dump($this->mem);
    }

    //退出登录
    public function logout()
    {
        session("mobile",null);
        return $this->redirect("/");
    }

    //登录
    public function login(Request $request)
    {
        if($request->isPost()){
            $validate = new \app\user\validate\User();
            if(!$validate->check($request->param())){
                $this->error($validate->getError());
            }
            $users['mobile'] = $request->param('mobile');
            $users['password'] = md5($request->param('password'));
            if($users['password'] == $this->mem->get($users['mobile'])) {
//                return json(['msg'=>"登陆成功"]);
                session('mobile',$users['mobile']);
                $this->mem->set($users['mobile'],$users['password']);
                return $this->redirect("/");
            }else{
                $ret = Db::table("user")->where(['mobile'=>$users['mobile']])->find();
                if($ret) {
                    if($ret['password'] == $users['password']){
                        session('mobile',$users['mobile']);
                        $this->mem->set($users['mobile'],$users['password']);
                        $this->redirect("/");
//                        return json(['msg'=>"登陆成功"]);
                    }else{
                        $this->error("用户密码错误");
                    }
                }else{
                    $this->error("用户不存在");
                }
            }
        }else{
            return view("login");
        }
    }

    //注册
    public function register(Request $request)
    {
        if($request->isPost()){
            $validate = new \app\user\validate\User();
            if(!$validate->check($request->param())){
                $this->error($validate->getError());
            }
            $users['mobile'] = $request->param('mobile');
            $ret =Db::table("user")->where($users)->find();
            if($ret){
                $this->error("用户已存在");
            }
            $users['password'] = md5($request->param('password'));
            $res = Db::table('user')->insertGetId($users);
            if($res){
                session('mobile',$users['mobile']);
                $this->mem->set($users['mobile'],$users['password']);
                $this->redirect("/");
            }
        }else{
            return view("register");
        }
    }
}
